package com.saunter.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if(null != cookies) {
            for(Cookie cookie : cookies) {
                if(cookie.getName().equals(key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
    public static void addCookie(HttpServletResponse response, String key, String value, int max_age, String path) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(path);
        if(max_age > 0)
            cookie.setMaxAge(max_age);
        response.addCookie(cookie);
    }
    public static void addCookie(HttpServletResponse response, String key, String value, int max_age) {
        addCookie(response, key, value, max_age, "/");
    }
    public static void addCookie(HttpServletResponse response, String key, String value) {
        addCookie(response, key, value, 3600, "/");
    }

    public static void addAdminCookie(HttpServletResponse response, String key, String value) {
        addCookie(response, key, value, 3600, "/admin");
    }
    public static void removeAdminCookie(HttpServletResponse response, String key) {
        addCookie(response, key, "", 1, "/admin");
    }

    public static void addUserCookie(HttpServletResponse response, String key, String value) {
        addCookie(response, key, value, 3600, "/user");
    }
    public static void removeUserCookie(HttpServletResponse response, String key) {
        addCookie(response, key, "", 1, "/user");
    }
    public static void updateCookie(HttpServletRequest request, HttpServletResponse response, String cookie_name, String key, String val, String path) {
        JSONObject old_cookie = JSONObject.parseObject(new String(Base64.decodeBase64(getCookie(request, cookie_name))));
        old_cookie.put(key, val);
        if("/admin".equals(path)) {
            addAdminCookie(response, cookie_name, Base64.encodeBase64String(JSON.toJSONBytes(old_cookie)));
        }else if("/user".equals(path)) {
            addUserCookie(response, cookie_name, Base64.encodeBase64String(JSON.toJSONBytes(old_cookie)));
        }
    }
    public static void updateAdminCookie(HttpServletRequest request, HttpServletResponse response, String cookie_name, String key, String val) {
        updateCookie(request, response, cookie_name, key, val, "/admin");
    }
    public static void updateUserCookie(HttpServletRequest request, HttpServletResponse response, String cookie_name, String key, String val) {
        updateCookie(request, response, cookie_name, key, val, "/user");
    }
}
